<template>
  <div class="mainua">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>新增设备</span>
          </div>
        </div>
        <div class="main_tile boxdq marginTop10">
          <div class="main_tile_l"><em></em>基本信息</div>
        </div>
        <div class="maincla_form">
          <el-form
            :model="formModel"
            :inline="true"
				:rules="rule"
            class="demo-form-inline"
            ref="form"
            label-width="110px"
          >
            <!-- 基本信息 -->
            <div>
              <el-form-item label="设备名称：" prop="name">
                <el-input
                  placeholder="设备名称"
                  clearable
                  v-model="formModel.name"
                  class="wid240"
                ></el-input>
              </el-form-item>

              <el-form-item label="编码(spu)：" prop="spu" label-width="180px">
                <el-input
                  placeholder="编码（spu）"
                  clearable
                  class="wid240"
                  v-model="formModel.spu"
                ></el-input>
              </el-form-item>

              <div class="clearfix"></div>
              <el-form-item label="上架状态：" prop="status">
                <el-switch
                  active-color="#03A98E"
                  active-text="开"
                  inactive-text="关"
						:active-value="1"
						:inactive-value="0"
                  v-model="formModel.status"
                  class="mainor_switch"
                ></el-switch>
              </el-form-item>
            </div>
            <!-- 商品主图及详情  -->
            <div class="main_tile boxdq">
              <div class="main_tile_l">
                <em></em>商品主图及详情
                <span>建议图片尺寸是:302*302，最多三张，主图为默认第一张</span>
              </div>
            </div>
            <div class="marginTop20 marginLeft10 main_upImg">
              <el-upload
                :action="uploadPath"
                list-type="picture-card"
					 :data="{store:'dev'}"
                :on-success="handSuccess"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :limit="3"
                :file-list="filelist"
              >
                <span slot="default">
                  <svg
                    aria-hidden="true"
                    class="main_page_svg"
                    width="32"
                    height="27"
                  >
                    <use xlink:href="#icon-commodit_camera" />
                  </svg>
                </span>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img :src="dialogImageUrl" alt />
              </el-dialog>
              <div class="clearfix"></div>
            </div>
            <div class="clearfix"></div>
            <div class="maincla_ed">
              <Editor
                apiKey="vl7byj8kh7hyvvi6o7137s7khcpfsp762987dlnbcd93u37a"
                v-model="formModel.detail"
                :init="setStore('dev')"
              ></Editor>
            </div>

            <!-- spu -->
            <div class="main_table row-expand-down">
              <el-table
                ref="multipleTable"
                :data="formModel.sku_list"
                element-loading-text="加载中"
                fit
                highlight-current-row
              >
				  	<el-table-column>
						<template slot-scope="scope">
						<!-- 增减行图标 -->
							<div class="maincla_sxf">
							<svg
								aria-hidden="true"
								class="main_page_svg"
								width="15"
								height="15"
								@click="plus"
							>
								<use xlink:href="#icon-commodity_plus" />
							</svg>
							<svg
								aria-hidden="true"
								class="main_page_svg"
								width="22"
								height="22"
								v-if="scope.$index != 0"
								@click="reduce(scope.$index)"
							>
								<use xlink:href="#icon-commodity_reduce" />
							</svg>
							</div>
						</template>
					</el-table-column>
                <el-table-column
                  label="规格/型号"
                  prop="model"
                  class-name="main_hei"
                  width="210"
                >
                  <template slot-scope="scope">
                      <el-form-item
                        :prop="'sku_list.' + scope.$index + '.model'"
								:rules="rule.model"
                        label-width="10px"
                        label=" "
                      >
                        <el-input
                          v-model.trim="scope.row.model"
                          placeholder="规格/型号"
                          clearable
                          class="wid110"
                        ></el-input>
                      </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="品牌"
                  prop="brand"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.brand'"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.brand"
                        placeholder="品牌"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="描述"
                  prop="describe"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.describe'"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.describe"
                        placeholder="描述"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="单位"
                  prop="unit"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.unit'"
							 :rules="rule.unit"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.unit"
                        placeholder="单位"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="编码（sku）"
                  prop="sku"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.sku'"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.sku"
                        placeholder="编码（sku）"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="原价"
                  prop="price_original"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.price_original'"
							 :rules="rule.price_original"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.price_original"
                        placeholder="原价"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="售价"
                  prop="price_selling"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.price_selling'"
							 :rules="rule.price_selling"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.price_selling"
                        placeholder="售价"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="库存"
                  align="center"
                  prop="use_inventory"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.use_inventory'"
                      label-width="10px"
                    >
                      <el-switch
                        v-model="scope.row.use_inventory"
                        active-color="#03A98E"
								:active-value="1"
								:inactive-value="0"
                        active-text="开"
                        inactive-text="关"
                        class="mainor_switch"
                      ></el-switch>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="库存数量"
                  prop="inventory"
                  class-name="main_hei"
                  width="180"
                >
                  <template slot-scope="scope">
                    <el-form-item
								v-if="scope.row.use_inventory"
								:prop="'sku_list.' + scope.$index + '.inventory'"
								:rules="rule.inventory"
								label-width="10px"
								label=" "
                    >
                      <el-input
                        v-model.trim="scope.row.inventory"
                        placeholder="库存数量"
                        clearable
                        class="wid110"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column
                  label="状态"
                  align="center"
                  fixed="right"
                  width="100"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'sku_list.' + scope.$index + '.status'"
                      label-width="10px"
                    >
                      <el-switch
                        v-model="scope.row.status"
                        active-color="#03A98E"
                        active-text="开"
                        inactive-text="关"
								:active-value="1"
								:inactive-value="0"
                        class="mainor_switch"
                      ></el-switch>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="clearfix"></div>
            <div class="newConBox_p200 paddingBottom10" id="newConBox">
              <div class="newConBox_h32">
                <div :class="['boxdq newConBox ', { on: searchBarFixed }]">
                  <div class="mainor_prl">
                    <el-button type="primary" @click="preservation(1)" v-repeatClick >保存并继续添加</el-button>
                    <el-button
                      class="reset marginLeft10"
                      type="info"
                      v-repeatClick
							 @click="preservation(2)"
                      >保存并返回列表</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";
import {setStore} from "./init";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { uploadPath } from "@/api/currency";
import {
  addDev,
} from "@/api/commodity/commodityDevlistEdit";
export default {
  components: {
    Editor,
  },
  data() {
	var validateNum = (rule, value, callback) => {
		if (typeof(Number(value))!=='number') {
			callback(new Error('请输入数字'));
		} else {
			callback();
		}
	};
    return {
		setStore,
      detail: "", //富文本详情
      //   上传图片
      filelist: [],
      uploadPath,
      dialogImageUrl: "",
      dialogVisible: false,
      // 监听滚动
      searchBarFixed: false,
      formModel: {
			name:'',
			spu:'',
			pic:'',
			pics:[],
			detail:'',
			status:false,
        	sku_list: [
				{use_inventory:false,status:false,model:'',describe:'',unit:'',sku:'',price_original:'',price_selling:'',inventory:0,}
			],
      },
		rule:{
			name:{required:true, message:'请输入名称',trigger:'blur'},
			// spu:{required:true, message:'请输入编码',trigger:'blur'},
			model:[
				{required:true, message:'请输入规格',trigger:'blur'},
			],
			unit:[
				{required:true, message:'请输入单位',trigger:'blur'},
			],
			price_original:[
				{required:true, message:'请输入原价',trigger:'blur'},
				{validator: validateNum, message:'请输入数字',trigger:'blur'},
			],
			price_selling:[
				{required:true, message:'请输入售价',trigger:'blur'},
				{validator: validateNum, message:'请输入数字',trigger:'blur'},
			],
			inventory:[
				{required:true, message:'请输入库存数量',trigger:'blur'},
				{validator: validateNum, message:'请输入数字',trigger:'blur'},
			],
		},
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
	 
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // SKU设置-加
		plus() {
			this.formModel.sku_list.push({use_inventory:false,status:false});
		},
		// SKU设置-减
		reduce(index) {
			this.formModel.sku_list.splice(index, 1);
		},
		//提交
		preservation(type){
			let dataModel = JSON.parse(JSON.stringify(this.formModel))
			dataModel.sku_list = JSON.stringify(dataModel.sku_list)
			// dataModel.pic = dataModel.pics[0]
			// dataModel.pics = JSON.stringify(dataModel.pics)
			dataModel.pic = dataModel.pics.length > 0 ? dataModel.pics[0].path : '';
			dataModel.pics = dataModel.pics.length > 0 ? dataModel.pics.map((p) => p.path).join(",") : '';
			this.$refs.form.validate((valid)=>{
				let validStatus = this.validStatus(dataModel.status,dataModel.sku_list);
			  if (valid && validStatus) {
					let data = Object.assign(
						{
							sign: Md5(
								objKeySort(Object.assign(apiUrl().name,dataModel)) + apiUrl().appsecret
							),
						},
						apiUrl().name,
						dataModel
					);
					addDev(data).then(res=>{
						if (res.errcode == 0) {
							this.$message({
								message: "新建成功",
								type: "success",
							});
							if(type==1){
								this.$refs.form.resetFields()
							}else{
								this.$router.go(-1);
							}
						} else {
							this.$message.error(res.errmsg);
						}
					})
				}
			})
		},

     //商品上架必须至少有一个sku状态为开
	validStatus(status,list){
		list = JSON.parse(list);
		if(Boolean(status)){
			for(let i in list){
				if(Boolean(list[i].status)){
					return true;
				}
			}
			this.$message.warning('商品上架必须至少一个sku状态为开')
			return false;
		}else{
			return true;
		}
	},

    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 上传图片-删除
	handleRemove(file) {
	  const i = this.formModel.pics.findIndex(
		(item) => item.path == file.path
	  );
	  this.formModel.pics.splice(i, 1);
	},
	// 上传图片-查看
	handlePictureCardPreview(file) {
	  this.dialogImageUrl = file.url;
	  this.dialogVisible = true;
	},
	// 上传图片-成功
	handSuccess(res, file, fileList) {
		this.formModel.pics.push({
		  name: "",
		  path: res.data.path,
		  url: res.data.src,
		});
		//文件过大上传失败是接口拒绝，但是组件还是默认上传成功了，所以要先加上数据上传失败再删掉
		if(res.errcode != 0){
			this.$message.error(res.errmsg);
			this.handleRemove(file)
		}
	},
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.maincla_form {
  /deep/.el-table .cell .el-table__expand-icon {
    display: none;
  }
  margin-left: 10px;
  margin-top: 10px;
  /deep/.el-form-item--mini.el-form-item,
  /deep/.el-form-item--small.el-form-item {
    margin-bottom: 22px;
  }
  .label_ids {
    display: block;
    /deep/.el-form-item__content {
      width: 85%;
    }
  }
  .maincla_lea {
    font-size: 0;
    span {
      min-width: 70px;
      padding-left: 10px;
      padding-right: 10px;
      height: 32px;
      line-height: 30px;
      display: inline-block;
      vertical-align: middle;
      align-items: center;
      text-align: center;
      font-size: $font_14;
      color: $colour_3;
      border: 1px solid $subActive;
      &:hover {
        cursor: pointer;
      }
      &.on {
        border-color: $menuActiveText;
        color: $menuActiveText;
      }
    }
  }
  .main_tile {
    margin-left: -10px;
  }
  .maincla_te {
    width: 59.7%;
    /deep/.el-form-item__content {
      width: calc(100% - 110px);
    }
  }
  .maincla_ed {
    margin-top: 20px;
    margin-left: 10px;
    width: 66%;
  }
  .maincla_ra {
    margin-top: 4px;
    margin-left: 30px;
    /deep/.el-radio {
      margin-right: 15px;
    }
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
    .maincla_sx {
      .maincla_sxf {
        margin-right: 15px;
        margin-left: 10px;
        margin-top: 2px;
        svg {
          display: block;
          &:nth-child(2) {
            margin-left: -4px;
            margin-top: 5px;
          }
          &:hover {
            cursor: pointer;
          }
        }
        use {
          fill: #c1c1c1ff;
        }
      }
      .maincla_sxf {
        svg {
          margin-left: 20px;
          fill: #c1c1c1ff;
        }
      }
      .maincla_sxs {
        width: 80px;
        margin-right: 20px;
        color: $colour_3;
      }
    }
    .maincla_dw {
      .maincla_dwp {
        .maincla_dwp_un {
          min-width: 90px;
          text-align: left;
          margin-right: 10px;
        }
        .wid110 /deep/.el-input__inner {
          width: 90px;
          padding-left: 0px;
        }
        /deep/.el-select .el-input .el-select__caret {
          font-weight: bold;
          color: $colour_3;
        }
        /deep/.el-input__inner {
          border: 0;
          background: none;
        }
        strong {
          width: 40px;
          line-height: 16px;
          display: inline-block;
          vertical-align: middle;
          color: $menuActiveText;
          margin-left: -7px;
        }
        &:hover {
          cursor: pointer;
          & strong {
            text-decoration: underline;
          }
        }
      }
      p {
        i {
          font-size: 18px;
          color: $menuText;
        }
      }
    }
    .maincla_bz {
      input {
        margin-right: 5px;
      }
    }
    /deep/.el-table tr.down td {
      border-bottom: 0;
    }
    .maincla_zh {
      margin-left: 517px;
      margin-bottom: 5px;
      margin-top: 10px;
      align-items: center;
      & > span {
        margin-right: 5px;
      }
      /deep/.el-select--small {
        margin-left: 5px;
      }
      p {
        color: $colour_red;
        margin-left: 10px;
        &:hover {
          cursor: pointer;
        }
      }
    }
  }
}
.row-expand-down /deep/.el-form-item__label {
  padding: 0 !important;
  width: 0 !important;
}
</style>